package ds.adt;

public class Digraph {

	private final int V;
	private int E;
	private Bag<Integer>[] adj;

	public Digraph(int V) {
		this.V = V;
		adj = (Bag<Integer>[]) new Bag[this.V];

		for (int i = 0; i < V; i++) {
			adj[i] = new Bag<Integer>();
		}
	}

	public void addEdge(int v, int w) {
		adj[v].add(w);
		E++;
	}

	public int V() {
		return V;
	}

	public int E() {
		return E;
	}

	public Iterable<Integer> adj(int v) {
		return adj[v];
	}

	public Digraph reverse() {
		Digraph dg = new Digraph(this.V);
		for (int v = 0; v < this.V; v++) {
			for (int w : adj(v)) {
				dg.addEdge(w, v);
			}
		}
		return dg;
	}

	public String toString() {
		String s = V + " vertices, " + E + " edges\n";
		for (int v = 0; v < V; v++) {
			s += v + ": ";
			for (int w : this.adj(v))
				s += w + " ";
			s += "\n";
		}
		return s;
	}
}
